package com.apes.fa.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fa.model.FaAssetInvest;
import com.apes.fa.model.FaAssetInvestItem;
import com.apes.fa.model.FaCard;
import com.apes.fa.model.FaCardAccount;
import com.apes.fa.respository.FaAssetInvestRepository;
import com.apes.fa.respository.FaCardAccountRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.IntStream;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fa.service
 * @ClassName: FaAssetInvestService
 * @Author: PengZiFeng
 * @Description: 投资转出/售卖
 * @CreateTime: 2021-09-08 15:16
 * @Version: 1.0
 */
@Service("faAssetInvestService")
public class FaAssetInvestService extends DomainService {

    @Autowired
    private FaAssetInvestRepository faAssetInvestRepository;
    @Autowired
    private FaCardAccountService faCardAccountService;
    @Autowired
    private FaCardService faCardService;

    /**
     * 保存
     */
    public FaAssetInvest save(SimpleRequest request){

        FaAssetInvest faAssetInvest = request.getO(FaAssetInvest.class);
        faAssetInvest.setState("create");
        return faAssetInvestRepository.saveAndFlush(faAssetInvest);

    }

    /**
     * 删除
     */
    public String delete(SimpleRequest request){
        FaAssetInvest faAssetInvest = request.getO(FaAssetInvest.class);
        faAssetInvestRepository.delete(faAssetInvest);
        return "删除成功！";
    }

    /**
     * 审核并生成投资转出卡片账
     */
    public FaAssetInvest approve(SimpleRequest request){

        FaAssetInvest faAssetInvest = request.getO(FaAssetInvest.class);
        faAssetInvest.setState("approve");
        faAssetInvest.setApproveDate(new Date());
        faAssetInvest.setApproveUid(this.getPerson(request));
        List<FaAssetInvestItem> faAssetInvestItems = faAssetInvest.getFaAssetInvestItems();
        for (FaAssetInvestItem faAssetInvestItem : faAssetInvestItems) {
            FaCard faCard = faAssetInvestItem.getFaCard();
            faCardAccountService.invest(faCard,request,faAssetInvestItem);
        }
        return faAssetInvestRepository.saveAndFlush(faAssetInvest);

    }

    /**
     * 投资转出/售卖 导入
     */
    public JSONObject importInfo(SimpleRequest request){
        //Excel信息
        JSONObject importData = request.get("importData");
        JSONArray field = (JSONArray) request.get("data");
        JSONObject exclObject = new JSONObject();                  //返回值

        JSONArray exclArr = new JSONArray();            //行内容
        JSONArray headerName = new JSONArray();         //头部
        JSONArray fieldName = new JSONArray();          //field
        for (Object o : field) {
            JSONObject webTab = (JSONObject) o;
            headerName.add(webTab.get("name"));
            fieldName.add(webTab.get("field"));
        }

        //获取model
        JSONObject model = (JSONObject) request.get("model");
        String deptId = model.getJSONObject("dept").getString("id");
        String businessType = "固定资产";

        //业务逻辑
        importData.forEach((k, v) -> {
            //获得value ===Excel内容
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //首行数据
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行

                if (i == 0) { //跳过首行
                    exclArr.add(headerName);
                    continue;
                }

                JSONArray lineLong = (JSONArray) excl.get(i); //当前行
                if (lineLong.size() == 0) {
                    continue; //跳过空白行
                }
                //合并2个list为一个map,KEY为首行数据，Value为当前行数据
                Map<String, String> rst = IntStream.range(0, header.size()).collect(HashMap::new,
                        (m, key) -> m.put(header.getString(key).replace(";", ""),
                                key >= lineLong.size() ? "" : (lineLong.getString(key) == null ? null : lineLong.getString(key).trim().replaceAll("[\\s]{2,}", " "))),
                        (m1, m2) -> {
                        });
                String faCardId = rst.get("卡片编码");

                request.setData(MapUtil.mapper(
                        "deptId",deptId,
                        "businessType",businessType,
                        "id",faCardId
                ));

                //根据条件查询可资产减少的卡片
                FaCard faCard = faCardService.findById(request);
                if(Objects.isNull(faCard)) continue;

                //累计折旧
                double accumulatedDepreciation = 0.0;

                List<FaCardAccount> faCardAccounts = SpringManager.getBean(FaCardAccountRepository.class).findAllByFaCardId(faCardId);
                if (!faCardAccounts.isEmpty() && faCardAccounts.size() != 0){
                    faCardAccounts.sort(Comparator.comparing(FaCardAccount::getBookkeepingDate).reversed());
                    accumulatedDepreciation = faCardAccounts.stream().findFirst().get().getAccumulatedDepreciation();
                }

                //用一个有序的map 封装数据, 防止乱序
                Map<String, Object> map = new LinkedHashMap<>();
                map.put("序号", "");
                map.put("卡片编码", faCard);
                map.put("商品编号", faCard.getProduct().getId());
                map.put("商品名称", faCard.getProduct().getName());
                map.put("成本中心名称", faCard.getDept().getCostCenterId().getName());
                map.put("资产去向", faCard.getFaWhereabouts());
                map.put("资产售价", faCard.getOriginalValue() - accumulatedDepreciation);

                //将map 转换成 list 利用stream流 引用Map类的getValue方法,弄成一个list
                List<Object> valueList = new ArrayList<>(map.values());
                exclArr.add(valueList);
            }
            exclObject.put(k, exclArr);
        });
        return exclObject;
    }

}
